package com.imb.security;

import com.imb.common.core.contract.SecurityConstant;
import com.imb.common.core.enums.PrErrorEnum;
import com.imb.common.core.enums.SecurityEnum;
import com.imb.common.core.jwt.JwtUtil;
import com.imb.common.web.exception.CustomException;
import com.imb.common.web.model.LoginUser;
import com.imb.common.web.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


/**
 *  统一鉴权
 * 我们需要自定义一个过滤器，这个过滤器会去获取请求头中的token，对token进行解析取出其中的userid。
 * ​ 使用userid去redis中获取对应的LoginUser对象。
 * ​ 然后封装Authentication对象存入SecurityContextHolder
 */

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("jwt请求头过滤");
        response.setHeader("Access-Control-Allow-Origin", "*");
        long start= System.currentTimeMillis();
        //获取token
        String token = request.getHeader(SecurityConstant.TOKEN);
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid= JwtUtil.parseJWTKey(token);
        //从redis中获取用户信息
        String redisKey = SecurityEnum.LOGIN_KEY.getValue() + userid;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            throw new CustomException(PrErrorEnum.ERROR_1002.getInfo(),PrErrorEnum.ERROR_1002.getCode());
        }
        if(!loginUser.getToken().equals(token)){
            throw new CustomException(PrErrorEnum.ERROR_1002.getInfo(),PrErrorEnum.ERROR_1002.getCode());
        }
        // TODO: 2023/2/25 续期
        redisCache.expire(SecurityEnum.LOGIN_KEY.getValue()+userid,24, TimeUnit.HOURS);
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
        //log.info("JWT"+(System.currentTimeMillis()-start));
    }
}
